import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/vuex'

import Dashboard from '@/views/dashboard/index.vue'
import workbench from '@/views/sys/workbench/index.vue'
/* eslint-disable */
import Home from '../views/Home.vue'
import Login from '../views/login/index.vue'
import Report from '@/components/report/Report.vue'
import ReportMore from '@/components/report/ReportMore.vue'
import Board from '@/components/report/Board.vue'
import indexModel from '@/views/frame/data-view/index-model.vue'

import strings from '@/util/strings.js'

const defaultSettings = require('../settings.js')

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
// eslint-disable-next-line import/no-dynamic-require
// const _import = require('./import-' + process.env.NODE_ENV)
// const _import = require.context('.', false, 'import-' + process.env.NODE_ENV)


Vue.use(VueRouter)
// const UserIndex = require('@/views/sys/user/index')

// 全局路由
const constantRoutes = [
  { path: defaultSettings.pathLogin, component: Login, name: 'login', meta: { title: '登录' } },
]

const mainRoute = {
  path: '/',
  component: Home,
  meta: { title: '工作台' },
  redirect: { path: '/dashboard' },
  children: [
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      meta: {
        requireAuth: true,
        title: '首页'
      }
    },
    {
      path: '/workbench',
      name: 'workbench',
      component: workbench,
      meta: {
        requireAuth: true,
        title: '工作台编辑'
      }
    },
  ]
}

const router = new VueRouter({
  mode: 'history',
  base: defaultSettings.pathRoot,
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: constantRoutes.concat(mainRoute)
})

let generateRouter = (menus)  => {
  let routes = []
  menus.forEach(item => {
    let route = null
    if (item.route && item.route.length > 0) {
      route = {
        name: item.name == null ? item.route : item.name,
        path: item.route,
        // component: _import(item.url),
        /*component: () => import(`@/views/${item.url}`),*/
        props: {
          propFlowKey: item.flowKey,
          propParameter: item.parameter
        },
        meta: {
          title: item.title,
          flowKey: item.flowKey
        }
      }
      let routerStr = item.route
      if (routerStr.indexOf('online/report/') != -1) {
        route.component = Report
        route.props.propReportKey = routerStr.substring(routerStr.lastIndexOf('/') + 1)
      } else if (routerStr.indexOf('online/board/') != -1) {
        route.component = Board
        route.props.propReportKey = routerStr.substring(routerStr.lastIndexOf('/') + 1)
      } else if (routerStr.indexOf('online/reportMore') != -1) {
        route.component = ReportMore
        route.props.propParameter = item.parameter
      } else if (strings.isNotBlank(item.viewKey)) {
        route.component = indexModel
        route.props.propViewKey = item.viewKey
        route.props.propFlowKey = item.flowKey
      } else if (strings.isNotBlank(item.url)) {
        route.component = (resolve) => require([`@/views/${item.url}`], resolve)
      }
      routes.push(route)
    }
    if (item.properties.url && item.properties.url.length > 0) {
      let  url = item.properties.url
      if (url.indexOf('.html') != -1) {// html 页面
        let name = url.replace('.html', '')
        route = {
          name: global.strings.replaceAll(name, '/', ''),
          path: name,
          // component: _import(item.url),
          /*component: () => import(`@/views/${item.url}`),*/
          props: {
          },
          meta: {
            title: item.title,
            flowKey: item.flowKey,
            htmlAddr: item.properties.url
          }
        }
        routes.push(route)
      }else if (url.indexOf('.vue') != -1) {// vue 页面
        let name = url.replace('.vue', '')
        name = global.strings.replaceAll(name, '/', '')
        name = global.strings.replaceAll(name, '-', '')
        route = {
          name: name,
          path: url.replace('.vue', ''),
          component: (resolve) => require([`@/views${url}`], resolve),
          props: {
          },
          meta: {
            title: item.title,
            flowKey: item.flowKey,
            htmlAddr: item.properties.url
          }
        }
        routes.push(route)
      }

    }
    if (item.children && item.children.length > 0) {
      routes = routes.concat(generateRouter(item.children))
    }
  })
  return routes
}

/**
 * 仅考虑二级菜单，将二级菜单加入到路由中
 * @param {Array} menus
 */
function addDynamicRoutes(menus = []) {
  let routes = generateRouter(menus)

  // mainRoute.name = 'main-dynamic'
  mainRoute.children = mainRoute.children.concat(routes)
  router.addRoutes([
    mainRoute
    // { path: '*', redirect: { name: 'PageNotFound' }  }
  ])
}


router.beforeEach((to, from, next) => {
  // 如果是登录或登出，放行
  if (to.path == defaultSettings.pathLogin || to.path == defaultSettings.pathLoginAll || to.path == '/logout') {
    console.log(111 + '  ' + to.path)
    next()
    return
  }

  let token = sessionStorage.getItem('X-Token')
  if (strings.isBlank(token)) {
    console.log(222 + '  ' + to.path)
    next({ path: defaultSettings.pathLogin })
    return
  }
  // 如果已经加载菜单列表
  if (router.options.isAddDynamicMenuRoutes) {
    next()
    return
  }

  global.$ajax.get('/upms/menus/navMenu', { params: { } }).then((response) => {
    if (response.code == 0) {
      let menus = response.data
      store.dispatch('setMenu', menus)
      if (menus.length == 0) {
        // 没有权限，禁止登录
        next(defaultSettings.pathLogin)
        global.utilMessage.error('跳转失败，请确认是否分配了菜单权限！')
        return
      }
      /*this.$router.options.routes[1].children = []
      this.generateRouter(this.menus)
      this.$router.addRoutes(this.$router.options.routes)*/

      addDynamicRoutes(menus)

      router.options.isAddDynamicMenuRoutes = true

      //访问不存在的或者没有权限
      let foundMenus = global.utils.findTreeNode(menus, m => (global.strings.isNotBlank(to.name) && m.route == to.name) || (global.strings.isNotBlank(to.url) && m.url == to.path)  ) || []
      if (foundMenus.length == 1) {
        next({...to, replace: true })
      } else {
        next({ path: '/' })
      }
    }
  })
})

/*const router = new VueRouter({
  routes
})*/
// router.beforeEach((to, from, next) => {
//   if (to.path === '/login' || to.path === '/logout') {
//     next()
//     return
//   }
//   // if (store.state.user.token === '') {
//   //   next('/login')
//   //   // 暂时关闭登录
//   // }
//   const token = sessionStorage.getItem('Auhtorization')
//   if (token === null || token === '') {
//     next('/login')
//     return
//     // 暂时关闭登录
//   }
//   next()
// })
export default router
